#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/healthz/views.py
# Compiled at: 2017-11-16 15:44:28
import os
from django.conf import settings
from django.http import JsonResponse
from .errors import CheckException
from .utils import ok_resp, failed_resp

def healthz(request):
    """
    health check
    """
    try:
        check_settings()
        check_db()
        check_third_api()
    except CheckException as e:
        return JsonResponse(failed_resp(message=e.get_message()))
    except Exception as e:
        return JsonResponse(failed_resp(message=u'ESB 服务检查异常：%s' % e))

    return JsonResponse(ok_resp(message='OK'))


def check_settings():
    """检查 settings 配置"""
    no_empty_settings_key = [
     'ESB_TOKEN', 'SSL_ROOT_DIR', 'PAAS_HOST', 'HOST_BK_LOGIN',
     'HOST_CC', 'HOST_JOB', 'HOST_DATA', 'HOST_FTA']
    for key in no_empty_settings_key:
        if not getattr(settings, key, ''):
            raise CheckException(u'settings 配置中 %s 不能为空' % key)

    if not os.path.exists(settings.SSL_ROOT_DIR):
        raise CheckException(u'settings 配置中 SSL_ROOT_DIR 指定的文件夹 %s 不存在' % settings.SSL_ROOT_DIR)
    ssl_files_config = {'JOB': ['job_esb_api_client.crt', 'job_esb_api_client.key']}
    for system_name, ssl_files in ssl_files_config.iteritems():
        for file_name in ssl_files:
            path = os.path.join(settings.SSL_ROOT_DIR, file_name)
            if not os.path.exists(path):
                raise CheckException(u'组件系统 %s 使用的 ssl 文件 %s 不存在' % (system_name, path))


def check_db():
    """检查 DB"""
    try:
        from esb.bkcore.models import ComponentSystem
        systems = ComponentSystem.objects.all()
        system_names = [ system.name for system in systems ]
    except Exception as ex:
        raise CheckException(u'数据库连接出现异常：%s' % ex)

    if not system_names:
        raise CheckException(u'组件系统及通道数据未初始化，请执行 "python manage.py sync_system_and_channel_data" 进行初始化')


def check_redis():
    try:
        import redis
        from common.base_redis import get_redis_pool, redis_config, redis_sentinel_config
        client = redis.Redis(connection_pool=get_redis_pool(redis_config, redis_sentinel_config))
        client.ping()
        key = 'esb_redis_check'
        client.set(key, 'esb')
        client.expire(key, 60)
        client.get(key)
    except Exception as ex:
        raise CheckException(u'Redis [%s:%s] [use_sentinel=%s] 连接出现异常：%s' % (
         settings.REDIS_HOST, settings.REDIS_PORT, getattr(settings, 'USE_SENTINEL', False), ex))


def check_third_api():
    """检查第三方系统API"""
    check_bk_login_api()
    check_cc_api()
    check_job_api()
    check_data_api()
    check_fta_api()


def check_bk_login_api():
    try:
        from components.bk.apis.bk_login.get_all_user import GetAllUser
        result = GetAllUser().invoke({'role': 1})
        if not result['result']:
            raise Exception(result['message'])
    except Exception as ex:
        raise CheckException(u'系统 BK_LOGIN 接口访问异常：%s' % ex)


def check_cc_api():
    try:
        from components.bk.apis.cc.get_set_property import GetSetProperty
        result = GetSetProperty().invoke()
        if not result['result']:
            raise Exception(result['message'])
    except Exception as ex:
        raise CheckException(u'系统 CC 接口访问异常：%s' % ex)


def check_job_api():
    try:
        from components.bk.apis.job.get_task import GetTask
        from esb.bkauth.models import User
        GetTask(current_user=User('admin')).invoke(kwargs={'app_id': 1})
    except Exception as ex:
        raise CheckException(u'系统 JOB 接口访问异常：%s' % ex)


def check_data_api():
    try:
        from components.bk.apis.data.data_component import DataComponent
        comp = DataComponent()
        comp.setup_conf({'dest_path': '/databus/get_encoding',
           'dest_http_method': 'GET'
           })
        result = comp.invoke()
        if not result['result']:
            raise Exception(result.get('message', u'出现未知错误'))
    except Exception as ex:
        raise CheckException(u'系统 DATA 接口访问异常：%s' % ex)


def check_fta_api():
    try:
        from components.bk.apis.fta.fta_component import FtaComponent
        from esb.component.base import CompRequest
        comp = FtaComponent()
        comp.set_request(CompRequest(headers={}, input={}))
        comp.setup_conf({'dest_path': '/event/api/1/',
           'dest_http_method': 'POST'
           })
        comp.invoke()
    except Exception as ex:
        raise CheckException(u'系统 FTA 接口访问异常：%s' % ex)
